<?php
/**
 * Create By: PhpStorm
 * User: yihua
 * File: GetUserCoupon.php
 * Date: 2017/1/6
 * Time: 2:25
 */

namespace app\api\model\page\user;

use app\library\Flag;
use app\library\PageBase;
use app\api\model\dao\UserCoupon;
use think\Log;
use app\library\Error;

class GetUserCoupon extends PageBase
{
    private $objUserCouponModel;

    public function __construct()
    {
        parent::__construct();
        $this->objUserCouponModel = new UserCoupon();
    }

    public function excute($param)
    {
        $ret = $this->checkToken($param);
        if (false === $ret) {
            return $this->getRes(Error::ERR_NO_AUTH);
        }
        $arrCouponInfo = $this->objUserCouponModel->getCouponByUserid($this->user_id);
        if (false === $arrCouponInfo) {
            return $this->getRes(Error::ERR_SYS);
        }
        $data = [];
        if (!empty($arrCouponInfo)) {
            foreach ($arrCouponInfo as $key => $value) {
                $value = $value->getData();
                $temp = json_decode($value['coupon_info'], true);
                $temp['start_time'] = date('Y.m.d', $temp['start_time']);
                $temp['end_time'] = date('Y.m.d', $temp['end_time']);
                $temp['type'] = Flag::$coupon_type[$temp['type']];
                $data[] = array_merge($value, $temp);
                unset($data[$key]['coupon_info']);
            }

        }
        if (isset($param['home']) && ('true' === $param['home'])) {
            $this->data = $this->composeData($data);
        } else {
            $this->data = $data;
        }
        return $this->getRes();

    }

    public function composeData($arrParam)
    {
        $data = [];
        $status = [
            1 => '未使用',
            2 => '已使用'
        ];
        foreach ($arrParam as $key => $value) {
            //$temp = [];
            $temp['start_time'] = isset($value['start_time']) ? date('Y-m-d H:i:s', $value['start_time']) : '';
            $temp['end_time'] = isset($value['end_time']) ? date('Y-m-d H:i:s', $value['end_time']) : '';
            $temp['status'] = isset($value['status']) ? $status[$value['status']] : $value['status'];

            array_push($data, array_merge($value, $temp));
        }
        return $data;

    }
}
